package com.itcam.servlet_.loginmodel.dao.impl;

import com.itcam.servlet_.loginmodel.dao.UserDao;
import com.itcam.servlet_.loginmodel.entity.User;

import java.sql.*;

/**
 * Author:Cammy.Wu
 * Date:2024-06-27
 * Description: 跟数据库发生交互
 */

public class UserDaoImpl implements UserDao {

    @Override
    public User checkUser(User user) {
        // 定义连接对象
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User u = null;

        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "990802");
            // 获取预处理块
            preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");
            // 给？赋值
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());

            // 执行sql
            resultSet = preparedStatement.executeQuery();
            // 从resultSet中获取数据
            while (resultSet.next()) {
                u = new User(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        return u;
    }
}
